Listening for New Messages With the Dart SDK
Background
Almost all actions in matrix are expressed as users
sending events
to rooms
. This makes intuitive sense when it comes to message events but works equally well for non-message events (e.g. add user event, change room name event, etc). When a user adds an event to a room, it is first added to the event graph on their personal client, then it is replicated to the user's home server and then it is replicated to all other clients that are in that room. Quiri is written in Dart and uses the matrix dart sdk to handle a lot of the client-server relationship. This includes maintaining the local copy of the current state of a room's state and listening for updates to that room's state. This guide goes into details about how that relationship is maintained so that we can build the quiri client appropriately.
Listening for events
On app startup, we currently call the init method. This method does a number of things including kicking off the first _sync request.
This sync call can be awaited as a whole, or you can provide the waitForFirstSync
as false
and instead await the roomsLoading
, _accountDataLoading
and userDeviceKeysLoading
futures individually. We will await on the init for now for simplicity.
After the initial sync, the client will begin a _backgroundSync that long polls every 30 seconds (configurable).
Replicating the state in the client
Each sync job uses the _handleSync method to perform the appropriate updates to state.
For example, in the _handleRoomEvents
sub-handler the updates are made in the following order:
- the in-memory state (accessible from the SDK client object e.g.
client.rooms
) - the client side database for persistent storage
- the SDK's exposed event streams
Reacting to new events in the UI
In particular, how do we know when new messages have arrived? Let's look at how Fluffychat does it. First let's look at where they render their chat boxes. The messages are found in a room's timeline
. The timeline
is returned from the SDK getTimeline method. An onUpdate
callback is passed to allow the UI to react to new messages arriving. Here is where Fluffychat sets up the timeline listener for new messages